package bbcache

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/sports"
	"sync"
)

type (
	Stats struct {
		MatchId int     `json:"match_id"`
		Type    int     `json:"type"`
		Home    float64 `json:"home"`
		Away    float64 `json:"away"`
	}

	BasketballStats struct {
		Type int     `json:"type"` // 统计类型
		Home float64 `json:"home"` // 主队统计
		Away float64 `json:"away"` // 客队统计
	}
	StatsCache struct {
		rds redis.UniversalClient
	}
)

var statsInstance *StatsCache
var statsOnce sync.Once

func NewStatsCache() *StatsCache {
	statsOnce.Do(func() {
		statsInstance = &StatsCache{
			rds: global.GetRds(),
		}
	})
	return statsInstance
}

// 计数统计key
func (s *StatsCache) getStatsKey(matchId int) string {
	return fmt.Sprintf("match_live:basketball_stats:%d", matchId)
}

// PublishStats 篮球计数统计数据
func (s *StatsCache) PublishStats(records []Stats) error {
	data := make(map[int][]BasketballStats, 0)
	for _, item := range records {
		data[item.MatchId] = append(data[item.MatchId], BasketballStats{
			Type: item.Type,
			Home: item.Home,
			Away: item.Away,
		})
	}
	pp := s.rds.Pipeline()
	for id, stats := range data {
		message := sports.BasketballStatsMessage{
			SentMessageStruct: messages2.SentMessageStruct{Type: messages2.StatsLiveMessageType},
			Stats:             stats,
		}
		marshal, _ := json.Marshal(message)
		err := pp.Set(s.getStatsKey(id), string(marshal), CacheExpire).Err()
		if err != nil {
			global.Log.Error("set cache err ", err)
			continue
		}
		imsdk.GetSdk().BroadcastInterface(id, message, 0)
	}

	_, err := pp.Exec()
	if err != nil {
		global.Log.Errorf("Pipeline run error: %v", err)
	}

	return nil
}

// GetStatsCache 获取计数统计缓存
func (s *StatsCache) GetStatsCache(matchId int) string {
	result, err := s.rds.Get(s.getStatsKey(matchId)).Result()
	if err != nil {
		return ""
	}
	return result
}
